const app = getApp()
console.log(app.data.levels,'app.data.levels')
Page({
  data: {
    authorize: false,
    dataSessionId: null,
    idIponeXFlag: false,
    userInfo: {},
    task: [],
    shareTpl: [
      `高能预警，没想到你是这样的小游戏`,
      `高能游戏，释放你的神奇力量`,
      `前方高能预警，复仇者正在集结！`,
      `高能预警！游戏有毒！请慎入！`,
      `高能游戏大爆发，这可能是前所未有的体验`
    ],
    levels: '',
    showBussCooper: false,
    formId: '',
    cooperation: {},
    showResiveFlag: '',
    showResiveTip: '',
    showResiveIcon: 0,
    upgrade:'',
    showUpgrade: false,
    
  },
  onLoad: function (options) {
    
  },
  //登录方法
  getuserinfo(ops) {
    const loginParams = ops.detail;
    if (ops.detail.errMsg === "getUserInfo:fail auth deny") {
      wx.showToast({ title: '请点击允许以获取信息!', icon: 'none' })
      return;
    }
    app.callLogin(loginParams).then(data => {
      this.setData({
        authorize: false,
        dataSessionId: wx.getStorageSync('sessionid_pro'),
      });
      wx.hideLoading();
      wx.showToast({ title: '登录成功' });
      this.getHomepage()
    })
  },
  
  //获取“我的”使用的数据
  getHomepage() {
    wx.request({
      url: app.data.commonUrl + app.data.homepage,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": 'Bearer ' + this.data.dataSessionId,
      },
      method: 'GET',
      success: res => {
        if (res.data.code === 0) {
          this.setData({
            userInfo: res.data.result.userinfo,
            task: res.data.result.task,
            cooperation: res.data.result.cooperation

          })
          if (res.data.result.userinfo) {
            let coin = res.data.result.userinfo.coin_total,
                level = res.data.result.userinfo.level,
                next_grow = res.data.result.userinfo.next_grow;
            
            app.data.current_num = res.data.result.task[3].current_num;
            app.data.game_current_num = res.data.result.task[1].current_num;
            app.data.share_current_num = res.data.result.task[2].current_num;
            //判断分享成功后，新用户点击进入小程序，则+500金币
            if (app.data.current_num != wx.getStorageSync('current_num')) {
              app.data.showResiveFlag = true;
              app.data.showResiveTip = '分享任务';
              app.data.showResiveIcon = 500;
            }
            //判断到达等级进阶后，显示升级的遮罩层
            if (wx.getStorageSync('level') && level != wx.getStorageSync('level')){
              this.setData({
                showUpgrade: true
              })
            }
            //方法调用
            app.judgeGrade(coin);
            this.setData({
              levels: app.data.levels
            })
            wx.setStorageSync('level', level);           
            wx.setStorageSync('current_num', app.data.current_num);
            
          }
        }
      }
    })
  },
  onShow() {
    //审查token是否过期，如果过期，清空Storage需要再次登录
    app.effectiveToken();

    let session_id = wx.getStorageSync('sessionid_pro');
    if (!session_id) {
      this.setData({
        authorize: true
      })
    } else {
      this.setData({
        authorize: false
      })
    }
    this.setData({
      idIponeXFlag: app.data.isIPhoneX,
      dataSessionId: wx.getStorageSync('sessionid_pro'),
      showResiveFlag: app.data.showResiveFlag,
      showResiveTip: app.data.showResiveTip,
      showResiveIcon: app.data.showResiveIcon
      
    })
    this.getHomepage()  
  },

  showBussCooperFn() {
    this.setData({
      showBussCooper: true
    })
  },
  hideBussCooper() {
    app.data.showResiveFlag = false;
    app.data.showResiveTip = '';
    app.data.showResiveIcon = 0;
    this.setData({
      showBussCooper: false,
      showUpgrade:false,
      showResiveFlag: app.data.showResiveFlag,
      showResiveTip: app.data.showResiveTip,
      showResiveIcon: app.data.showResiveIcon
    })
  },
  //领取的任务发送task请求
  requestFn(task_name) {
    wx.request({
      url: app.data.commonUrl + app.data.taskUrl,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": 'Bearer ' + this.data.dataSessionId,
      },
      method: 'GET',
      data: {
        task_name: task_name,
        appflag: app.data.appflag
      },
      success: res => {
        if (res.data.code === 0) {
          this.getHomepage();

        }
      }
    })
  },
  //点击领取
  submit(e) {
    let task_name = e.detail.target.dataset.type;
    this.setData({
      formId: e.detail.formId
    })
    this.counteData(task_name);

  },
  //点击领取或者确定的按钮，每天把点击的第一次发送pushNotification请求
  counteData(id) {
    let day = new Date();
    day.setTime(day.getTime());
    let s2 = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate(),
      push_id = wx.getStorageSync('push_id_my_' + s2),
      str_push_id = id;
    if (push_id == str_push_id) {
      this.myReceive(str_push_id)
    } else {
      wx.request({
        url: app.data.commonUrl + app.data.pushNotification,
        method: 'POST',
        data: {
          token: this.data.formId,
          appflag: 'xcx06'
        },
        success: res => {
          this.myReceive(str_push_id)
        }
      })
      wx.setStorageSync('push_id_my_' + s2, id)

    }
  },
  //领取成功后的遮罩层显示
  myReceive(task_name) {
    if (task_name == 'check_in') {
      app.data.showResiveFlag = true;
      app.data.showResiveTip = '每日签到任务';
      app.data.showResiveIcon = 100;
      this.setData({
        showResiveFlag: app.data.showResiveFlag,
        showResiveTip: app.data.showResiveTip,
        showResiveIcon: app.data.showResiveIcon
      })

      this.requestFn('check_in')

    } else if (task_name == 'enter_game') {
      //进入游戏页面
      wx.switchTab({
        url: '../index/index',

      })
    } else if (task_name == 'share') {
      this.onShareAppMessage()
    } else if (task_name == 'lottery'){
      this.luckDraw()
    }

  },
  //复制文本
  copyText(e) {
    let copy_data = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: copy_data,
      success: res => {
        wx.showToast({
          title: '复制成功~',
          icon: 'none',
          duration: 1500,
          mask: true,
          isDone: false
        })
      }
    })
  },
  onShareAppMessage(res) {
    const index = ~~(Math.random() * app.data.shareTpl.length),
      tplIndex = index + 1,
      _this = this,
      openid = wx.getStorageSync('openid');
    return {
      title: app.data.shareTpl[index],
      path: `/pages/index/index?shareTpl=${tplIndex}&task_intval_friend=${openid}`,
      imageUrl: `/resourse/ad${tplIndex}.jpg`,
      success: function (res) {
        wx.showToast({
          title: '快让你的好友一起来玩游戏吧~',
          icon: 'none',
          duration: 1500,
          mask: true,
          isDone: false
        })
      },
      fail: function (res) {

      }
    }
  },
  //进入转盘抽奖
  luckDraw() {
      wx.navigateTo({
        url: '/pages/turntable/turntable',
      })
    
  } 
})
